<template>
  <div class="app-container">
    <el-row :gutter="15">
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>部门用户列表</span>
            </div>
          </template>
          <div>
            <el-tree
              :data="deptTree"
              v-loading="loading"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
              :props="{ children: 'children', label: 'deptName' }"
              @node-click="openDept"
            />
          </div>
        </el-card>
      </el-col>

      <el-col :span="16">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>部门用户列表</span>
              <el-button
                v-if="deptCode !== ''"
                style="float: right; padding: 3px 0"
                link
                type="primary"
                @click="handleMenuButton()"
              >
                关联用户
              </el-button>
            </div>
          </template>
          <div>
            <el-table
              :data="userList"
              border
              style="width: 100%"
              v-loading="tableLoading"
              highlight-current-row
            >
              <el-table-column
                align="center"
                label="序号"
                type="index"
                width="65"
              />
              <el-table-column prop="account" align="center" label="用户账号" />
              <el-table-column
                prop="userName"
                align="center"
                label="用户姓名"
              />
              <el-table-column
                prop="mobilePhone"
                align="center"
                label="联系方式"
              />
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="150"
              >
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    @click="handleDelete(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pager-wrapper">
            <el-pagination
              background
              :layout="paginationData.layout"
              :page-sizes="paginationData.pageSizes"
              :total="paginationData.total"
              :page-size="paginationData.limit"
              :currentPage="paginationData.page"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 部门用户新增 -->
    <DeptUserTableDialog
      v-if="dialogVisible"
      :deptCode="deptCode"
      :closedDialog="handleMenuButtonClosedDialog"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount } from "vue";
import UserAPI, { type UserVO } from "@/api/system/base/user";
import DeptAPI, { type DeptVO } from "@/api/system/base/dept";
import { usePagination } from "@/hooks/usePagination";
import { ElMessageBox } from "element-plus";
import DeptUserTableDialog from "@/views/system/base/deptUser/components/DeptUserTableDialog.vue";

/** 部门用户管理 */
defineOptions({
  name: "BaseDeptUser",
});
/** 部门用户弹窗状态 */
const dialogVisible = ref<boolean>(false);
/** 部门用户状态 */
const loading = ref<boolean>(false);
/** 按钮状态 */
const tableLoading = ref<boolean>(false);
/** 部门树 */
const deptTree = ref<DeptVO[]>([]);
/** 表格数据 */
const userList = ref<UserVO[]>([]);
/** 部门用户编码 */
const deptCode = ref<string>("");

/** 翻页状态 */
const { paginationData, handleCurrentChange, handleSizeChange } =
  usePagination();

/** 部门树接口 */
const getDeptTree = () => {
  loading.value = true;
  // 初始化部门树
  DeptAPI.getBaseDeptTreeApi({})
    .then((res) => {
      const { status, data } = res;
      if (res && status === 200) {
        deptTree.value = data;
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

/** 打开添加部门用户按钮弹窗 */
const handleMenuButton = () => {
  dialogVisible.value = true;
};
/** 关闭弹窗 */
const handleMenuButtonClosedDialog = (data: boolean) => {
  // 有值，则刷新列表
  if (data) {
    getTableData();
  }
  dialogVisible.value = false;
};
/** 获取部门用户列表 */
const getTableData = () => {
  if (deptCode.value) {
    tableLoading.value = true;
    UserAPI.getDeptUsersByDeptCodeApi(deptCode.value, {
      page: paginationData.page,
      limit: paginationData.limit,
    })
      .then((res) => {
        const { status, data } = res;
        if (status === 200) {
          userList.value = data.rows;
          paginationData.total = data.total;
        }
      })
      .finally(() => {
        tableLoading.value = false;
      });
  }
};

/** 删除部门用户按钮 */
const handleDelete = (row: UserVO) => {
  ElMessageBox.confirm(
    `正在删除 "${row.userName}" 的部门用户关系，确认删除？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    row.id &&
      DeptAPI.delDeptUserByUserIdApi(deptCode.value, row.id).then((res) => {
        const { status, message } = res;
        if (status === 200) {
          getTableData();
          ElMessage.success("删除成功");
        } else {
          ElMessage.error(message);
        }
      });
  });
};
/** 点击部门用户 */
const openDept = (node: DeptVO) => {
  deptCode.value = node.deptCode!;
  getTableData();
};

/** 页面渲染完成后初始化 */
onBeforeMount(async () => {
  getDeptTree();
});

/** 监听分页参数的变化 */
watch([() => paginationData.page, () => paginationData.limit], getTableData, {
  immediate: true,
});
</script>

<style lang="scss" scoped>
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
